package com.wjbgn.gobang.server.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjbgn.gobang.server.user.entity.GameLogDO;
import com.wjbgn.gobang.server.user.entity.UserIntegralDO;
import com.wjbgn.gobang.server.user.mapper.UserIntegralMapper;
import com.wjbgn.gobang.server.user.service.GameLogService;
import com.wjbgn.gobang.server.user.service.UserIntegralService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * Description:
 * Create Date: 2022-04-07T10:29:18.521
 *
 * @author wjbgn
 * @version 1.0
 */
@Service
public class UserIntegralServiceImpl extends ServiceImpl<UserIntegralMapper, UserIntegralDO> implements UserIntegralService {

    @Autowired
    private GameLogService gameLogService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateIntegral(UserIntegralDO userIntegralDO, Boolean flag) {

        try {
            boolean update = gameLogService.update(new GameLogDO(flag ? "1" : "2", LocalDateTime.now()),
                    new QueryWrapper<>(new GameLogDO("3", userIntegralDO.getUsername())));
            if (update) {
                UserIntegralDO userIntegral = new UserIntegralDO(userIntegralDO.getUsername(), userIntegralDO.getType());
                // 获取当前用户的积分
                UserIntegralDO one = this.getOne(new QueryWrapper<>(userIntegral));

                if (one.getIntegral() == 0 && !flag) {
                    return true;
                } else if ((one.getIntegral() > 0 && one.getIntegral() < 10) && !flag) {
                    this.lambdaUpdate().getBaseMapper().update(
                            new UserIntegralDO(0),
                            new QueryWrapper<>(userIntegral));
                } else {
                    this.lambdaUpdate().getBaseMapper().update(
                            new UserIntegralDO(one.getIntegral() + (flag ? 100 : -10)),
                            new QueryWrapper<>(userIntegral));
                }
            } else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
}